'use strict';

let md5 = require('md5');
const CLI = {
    "id": 1,
    "clientId": 'app',
    "clientSecret": 'yto',
    "refreshTokenLifetime": 0,
    "accessTokenLifetime": 0,
    "grants": [
        "password"
    ]
};
module.exports = app => {

    class Model {
        constructor(ctx) {
            this.ctx = ctx;
        }
        async getClient(clientId, clientSecret) {
            if (clientId === 'app' && clientSecret === 'yto') {
                return CLI;
            }
            return;
        }
        async getUser(username, password) {
            const user = await this.ctx.service.user.login(username);
            if (!user) {
                callback(null, null);
                return;
            }
            const bo = md5(password) === user.password;
            if (!bo) {
                return;
            } else {
                return { id: user._id };
            }
        }
        async getAccessToken(bearerToken) {
            let db = await app.model.Oauth.findOne({accessToken:bearerToken});
            const token = db;
            token.client = CLI;
            this.ctx.session.userId = db.user.id;
            return token;
        }
        async saveToken(token, client, user) {
            const _token = Object.assign({}, token, { user }, { client });
            await app.model.Oauth(Object.assign({}, token, { user })).save();
            return _token;
        }

    }
    return Model;
}

